package com.daigou.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daigou.dao.UserMapper;
import com.daigou.dto.AjaxResult;
import com.daigou.dto.ServiceResult;
import com.daigou.dto.UserQuery;
import com.daigou.mail.SendMail;
import com.daigou.model.User;
import com.daigou.service.UserService;
import com.daigou.tools.GenerateUUID;
import com.daigou.tools.Md5;
import com.daigou.tools.RandomPassword;

/**  
 * @Title: UserServiceImpl.java
 * @Package com.daigou.service
 * @Description: TODO
 * @author lizhi
 * @date 2018年3月27日
 */
@Service("userService")  
public class UserServiceImpl implements UserService {
	@Autowired  
	protected UserMapper userInfoMapper;
	
	public User login(String loginName,String pwd) {
		//小写存储
		pwd = Md5.MD5(pwd.trim().toLowerCase());
		User user = userInfoMapper.login(loginName,pwd);
		if(user != null){
			user.setPwd(Md5.MD5(user.getId()+"_"+user.getLoginName()+"_"+user.getPwd()));
		}
		return user;
	}
	
	public User selectAllUser(User userinfo){
		return null;
	}
	
	public User selectByPrimaryKey(Long id){
		return userInfoMapper.selectByPrimaryKey(id);
	}
	/**
	 * 为订单写的插入用户信息
	 * @param orderUser
	 * @return
	 */
	public ServiceResult insertOrUpdate4Order444(User orderUser){
		User userDb = userInfoMapper.selectByLoingName(orderUser.getLoginName().trim());
		try{
			if(orderUser.getEmail() != null && !"".equals(orderUser.getEmail())){
				User userEmail = userInfoMapper.selectByEmail(orderUser.getEmail());
				if(userEmail != null){
					if(!userEmail.getLoginName().equals(orderUser.getLoginName().trim())){
						return new ServiceResult(false,"用户邮箱已存在!");
					}
				}
			}
    		if(userDb == null){
    			orderUser.setId(GenerateUUID.generateUUID());
    			orderUser.setType(2);//2代表买家
    			orderUser.setCreatedTime(new Date());
    			//如果传入，则使用传入的人的，如果不传，则默认自己创建的
    			orderUser.setCreatorId(orderUser.getId());
    			userInfoMapper.register(orderUser);
    			return new ServiceResult(true, "用户新增成功！",orderUser);
    		}else{
    			userDb.setName(orderUser.getName());
    			userDb.setMobile(orderUser.getMobile());
    			userDb.setLoginName(orderUser.getLoginName());
    			userDb.setWeixin(orderUser.getWeixin());
    			userDb.setEmail(orderUser.getEmail());
    			userDb.setAddress(orderUser.getAddress());
    			userInfoMapper.updateByPrimaryKeySelective(userDb);
    			return new ServiceResult(true, "用户更新成功！",userDb);
    		}
    	}catch(Exception ex){
    		ex.printStackTrace();
    		return new ServiceResult(false, "用户更新失败,请刷新后重试或直接联系管理员！");
    	}
	}
	
	
	public ServiceResult register(User userInfo){
		User userDb = userInfoMapper.selectByLoingName(userInfo.getLoginName());
		//如果userDb != null，表示用户已存在
		if(userDb != null){
			return new ServiceResult(false,"用户已存在!");
		}else{
			//暂时不校验邮箱了
			/*if(userInfo.getEmail() != null && !"".equals(userInfo.getEmail())){
				User userEmail = userInfoMapper.selectByEmail(userInfo.getEmail());
				if(userEmail != null){
					if(!userEmail.getLoginName().equals(userInfo.getLoginName().trim())){
						return new ServiceResult(false,"用户邮箱已存在!");
					}
				}
			}*/
			Long uId = GenerateUUID.generateUUID();
			userInfo.setId(uId);
			userInfo.setSex(-1);
			userInfo.setName(userInfo.getLoginName());
			userInfo.setStatus(10);
			userInfo.setMobile(userInfo.getLoginName());
			userInfo.setCreatedTime(new Date());
			userInfo.setCreatorId(uId);
			//小写存储
			userInfo.setPwd(userInfo.getPwd().toLowerCase());
			userInfo.setPwd(Md5.MD5(userInfo.getPwd()));
			userInfoMapper.register(userInfo);
			if(userInfo != null){
				userInfo.setPwd(Md5.MD5(userInfo.getId()+"_"+userInfo.getLoginName()+"_"+userInfo.getPwd()));
			}
			return new ServiceResult(true,"注册成功!",userInfo);
		}
	}
	/**
	 * 员工的新增和保存
	 * @param employee
	 * @return
	 */
	public ServiceResult insertOrUpdateEmployee(User employee){
		User userDb = userInfoMapper.selectByLoingName(employee.getLoginName());
		//如果userDb != null，表示用户已存在
		if(userDb != null){
			//无归属店铺或者属于当前店铺，则进行更新操作
			if(userDb.getShopId() == null || employee.getShopId().equals(userDb.getShopId())){
				//暂时不校验邮箱了
				/*if(employee.getEmail() != null && !"".equals(employee.getEmail())){
					User userEmail = userInfoMapper.selectByEmail(employee.getEmail());
					if(userEmail != null){
						if(!userEmail.getLoginName().equals(employee.getLoginName().trim())){
							return new ServiceResult(false,"用户邮箱已存在!");
						}
					}
				}*/
				userDb.setShopId(employee.getShopId());
				//员工默认是20
				userDb.setStatus(20);
				userDb.setName(employee.getName());
				userDb.setMobile(employee.getLoginName());
				//员工的保存，不是2就是3
				if(employee.getType() == null || (2 != employee.getType() && 3 != employee.getType())){
					employee.setType(3);
				}
				userDb.setType(employee.getType());
				userDb.setEmail(employee.getEmail());
				userDb.setSex(employee.getSex());
				userDb.setWeixin(employee.getWeixin());
				userDb.setWeixinQrCode(employee.getWeixinQrCode());
				userDb.setIdCard(employee.getIdCard());
				userDb.setAddress(employee.getAddress());
				userDb.setQq(employee.getQq());
				//上级领导
				userDb.setLeaderId(employee.getLeaderId());
				userDb.setLeaderName(employee.getLeaderName());
				//更新时，不更新密码，通过重置密码来解决忘记密码问题
				userDb.setPwd(null);
				userDb.setPwd(null);
				userInfoMapper.updateByPrimaryKeySelective(userDb);
			}else{
				return new ServiceResult(false,"用户手机号已存在!");
			}
		}else{
			//暂时不校验邮箱了
			/*if(employee.getEmail() != null && !"".equals(employee.getEmail())){
				User userEmail = userInfoMapper.selectByEmail(employee.getEmail());
				if(userEmail != null){
					return new ServiceResult(false,"用户邮箱已存在!");
				}
			}*/
			Long uId = GenerateUUID.generateUUID();
			employee.setId(uId);
			//员工默认是20
			employee.setStatus(20);
			employee.setMobile(employee.getLoginName());
			//小写存储
			employee.setPwd(employee.getPwd().toLowerCase());
			employee.setPwd(Md5.MD5(employee.getPwd()));
			userInfoMapper.insertEmployee(employee);
			if(employee != null){
				employee.setPwd(Md5.MD5(employee.getId()+"_"+employee.getLoginName()+"_"+employee.getPwd()));
			}
		}
		return new ServiceResult(true,"员工创建成功!");
	}
	public User selectByLoingName(String loginName){
		return userInfoMapper.selectByLoingName(loginName);
	}
	/**
	 * 通过email查找用户id
	 * @param uId
	 * @return
    */
	public User selectByEmail(String email){
		return userInfoMapper.selectByEmail(email);
	}
	/**
	 * 忘记密码
	 * @param email
	 * @return
	 */
	public AjaxResult forgetPassword(String email){
		User userInfo = selectByEmail(email);
		AjaxResult ajaxResult = new AjaxResult(true);
		if(userInfo != null){
			String pwd = RandomPassword.generateRandomPassword(6);
			String md5Pwd = Md5.MD5(pwd);
			int result = userInfoMapper.updatePasswordByEmail(email,md5Pwd);
			if(result == 1){
				try{
					boolean isSucc = SendMail.sendMail4GetPwd(userInfo,pwd);
					if(isSucc){
	    				ajaxResult.setMessage("已经将随机密码发送到您的\""+email+"\"邮箱，为了您的信息安全，请您收到后立即修改！");
	    				return ajaxResult;
	    			}else{
	    				ajaxResult.setSuccess(false);
	    				ajaxResult.setMessage("请检查您的邮箱格式！");
	    				return ajaxResult;
	    			}
		    	}catch(Exception ex){
		    		ajaxResult.setSuccess(false);
    				ajaxResult.setMessage("请检查您的邮箱格式！");
    				return ajaxResult;
		    	}
			}
		}
		ajaxResult.setSuccess(false);
		ajaxResult.setMessage("未查询到您注册的邮箱，请确认邮箱名称是否正确！");
		return ajaxResult;
	}
	
	public int updatePasswordByEmail(String email,String pwd){
		return userInfoMapper.updatePasswordByEmail(email,pwd);
	}
	
	public int updatePasswordById(Long id,String pwd){
		pwd = Md5.MD5(pwd.toLowerCase());
		return userInfoMapper.updatePasswordById(id,pwd);
	}
	
	public int updateByPrimaryKeySelective(User userInfo){
		return userInfoMapper.updateByPrimaryKeySelective(userInfo);
	}
	/**
	 * 从订单汇总我所有的客户
	 * @param userId
	 * @return
	 */
	public List<User> selectMyEmployee(UserQuery userQuery){
		return userInfoMapper.selectMyEmployee(userQuery);
	}

	/**
	 * 通过shopId查找管理员
	 * 
	 * @param shopId
	 * @return
	 */
	public User selectAdminUser(Long shopId) {
		return userInfoMapper.selectAdminUser(shopId);
	}
}  